<?php

namespace App\Task;

use App\Cache\SocketRoom;
use App\Service\SocketClientService;
use Carbon\Carbon;
use Hyperf\Crontab\Annotation\Crontab;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Redis\Redis;
use Hyperf\Utils\ApplicationContext;

/**
 * @Crontab(name="chat-count", rule="*\/10 * * * * *", callback="execute", memo="")
 */
class WsSendChatCountTask
{
    /**
     * @Inject()
     * @var Redis
     */

    private $redisServer;


    public function execute()
    {
        $now = Carbon::now()->toDateTimeString();
//        $groups = Db::table('group')
//            ->where('start_time', '<', $now)
//            ->where('end_time', '>', $now)
//            ->get();
        $r = redis()->keys('rds-set:ws:room:*');
        foreach ($r as $group) {
            continue;
//            $id = data_get($group, 'id', '');
            $id = str_replace('rds-set:ws:room:', '', $group);

            $userIdByRoom = redis()->sMembers('rds-set:ws:room:'.$id);

            if (!$userIdByRoom) {
                continue;
            }
            foreach ($userIdByRoom as $roomUserId) {
                $pingTime = redis()->hGet('chat-ping', $roomUserId);
                if (Carbon::now()->subSeconds(60)->toDateTimeString() > $pingTime ) {
                    redis()->hDel('chat-ping', $roomUserId);
                    redis()->sRem($group, $roomUserId);
                }
            }
            $count = count($userIdByRoom);

            info('直播间人数', [$group, $count]);
            $clientService = new SocketClientService();
            $fds = [];
            foreach (SocketRoom::getInstance()->getRoomMembers(strval($id)) as $uid) {
                $fds[] = $clientService->findUserFds(intval($uid));
            }

//        info('mes', [$message, $fds]);
            $sender = new \Hyperf\WebSocketServer\Sender(ApplicationContext::getContainer());
            if (empty($fds)) return;

            $fds = array_unique(array_merge(...$fds));

            // 客户端ID去重
            if (!$fds) return;

            if ($fds) {
                try {
                    foreach ($fds as $fd) {
                        $res = $sender->push((int)$fd, json_encode(['event' => 'chat_count', 'content' => [
                            'count'   => $count,
                        ]]));
                    }
                } catch (\Exception $e) {}
            }
        }

        foreach ($groups as $group) {

        }
    }
}
